#include "mpHttpResponseFileContent.h"
#include "mpFileUtils.h"
#include "mpLog.h"

namespace MP{
namespace HTTP{
namespace INTERNAL{

HttpResponseFileContent::HttpResponseFileContent(const std::string& filePath,
                                                 std::size_t fileOffset)
    :_filePath(filePath),_fileOffset(fileOffset)
{

}

HttpResponseFileContent::~HttpResponseFileContent() {
    endReadData();
}

bool HttpResponseFileContent::isHttpResponseFileContent(){
    return true;
}

void HttpResponseFileContent::beginReadData(){

    _isCanWriteFile = false;

    try{

        if(MP::FileUtils::create_directories_forfile(_filePath))
        {
            if(!_file_write.is_open()){
                //文件的打开方式：http://www.manongjc.com/detail/51-ttjsxwcybflksbj.html
                _file_write.open(_filePath,std::ios::out|std::ios::binary);
            }

            if(_file_write.is_open()){
                _file_write.seekg(_fileOffset,std::ios::beg);
                _isCanWriteFile = true;
            }
            else{
#if defined(MAPLE_MODE_DEBUGGING)
                MPLOG_INFO << "HttpResponseFileContent open file fail . " << _filePath;
#endif
            }
        }
    }
    catch(...){
        MPLOG_ERROR << "HttpResponseFileContent beginReadData err .";
    }


}

void HttpResponseFileContent::onReadDataSome(const char* data, std::size_t length){
    if(_isCanWriteFile){
        _file_write.write(data,length);
    }
}

void HttpResponseFileContent::endReadData(){
    try{

        if(_file_write.is_open()){
            _file_write.close();
            //            //如果文件为空，则删除
            //            std::size_t size = MP::FileUtils::get_file_size(_filePath);
            //            if(size == 0){
            //                MP::FileUtils::remove_file(_filePath);
            //            }
        }
    }
    catch(...){
        MPLOG_ERROR << "HttpResponseFileContent endReadData err .";
    }
}

}   //INTERNAL
}   //HTTP
}   //MP
